package org.swift.mashup.engine.model;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class When {

	private String rawCondition;
	
	private String condition;
	
	private Map<String, Constant> constants = new HashMap<String, Constant>();

	private Map<String,String> namespaces;
	
	public When(String condition, Map<String, ? extends Constant> constants, Map<String,String> namespaces){
		this.rawCondition = condition;		
		this.condition = parseCondition(condition, constants);
		this.constants.putAll(constants);
		this.namespaces = namespaces;
	}

	public String getRawCondition() {
		return rawCondition;
	}
	
	public String getCondition() {
		return condition;
	}
	
	private String parseCondition(String condition, Map<String, ? extends Constant> constants) {
		for (Entry<String, ? extends Constant> constant: constants.entrySet()) {
			condition = condition.replaceAll(
					escapeRegEx(constant.getKey()), "\"" + constant.getValue().getValue() + "\"");
		}
		return condition;
	}
	
	
	private static String escapeRegEx(String inStr) {
		return inStr.replaceAll("([\\\\*+\\[\\](){}\\$.?\\^|])", "\\\\$1");	
	}

	public Map<String,String> getNamespaces() {
		return namespaces;
	}

}
